package com.shanghaionstar.user;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.mag.joinme.RegisterToVisitorResponse;
import com.onstar.cn.map.util.ToastUtil;
import com.onstar.cn.notify.NotifyCodeReq;
import com.onstar.cn.notify.NotifyConfigRes;
import com.onstar.cn.smart.BaseResponse;
import com.onstar.cn.weight.TimeButton;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.MoreActivity;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.notifysetting.presenter.NotifyPresenter;
import com.shanghaionstar.user.iview.IChangeEmailOrPhoneView;
import com.shanghaionstar.user.presenter.ChangeEmailOrPhonePresenter;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.weight.CommonInputLayout;
import com.shanghaionstar.weight.CommonProgressButton;
import com.shanghaionstar.weight.TopLayout;

import static com.shanghaionstar.OnstarApplication.getApplication;
import static com.shanghaionstar.user.presenter.ChangeEmailOrPhonePresenter.INotifyProcessType.GET_CODE;
import static com.shanghaionstar.user.presenter.ChangeEmailOrPhonePresenter.INotifyProcessType.SET_CONFIG;
import static com.shanghaionstar.user.presenter.ChangeEmailOrPhonePresenter.INotifyProcessType.VALIDATE_CODE;

/**
 * Created by 7828wc on 16/7/18.
 */
public class ChangeEmailOrPhoneFragment extends BaseFragment implements IChangeEmailOrPhoneView {
    @FindViewById
    private TextView tv_user_info, tv_user_info_value, tip_tv;
    @FindViewById
    private RelativeLayout user_info_layout;
    @FindViewById
    private CommonInputLayout et_new_user_info, et_verify_code;
    @FindViewById
    private TimeButton btn_get_code;
    @FindViewById
    private CommonProgressButton btn_submit;
    @FindViewById
    private TopLayout top_layout;
    private ChangeEmailOrPhonePresenter presenter;
    private boolean isGetCode = false;
    private boolean isEmail = false;

    private boolean isFromNotify;
    private NotifyConfigRes mNotifyConfigRes;
    private static String phoneNum;

    @Override
    public int getLayoutId() {
        return R.layout.more_change_email;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setListener();
    }

    private void setListener() {
        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (presenter.verifyInput(et_new_user_info, isEmail) && presenter.verifyInputCode(et_verify_code)) {
                    isGetCode = false;
                    if (!isFromNotify) {
                        presenter.setUserInfo(isEmail ? et_new_user_info.getText() : "", !isEmail ? et_new_user_info.getText() : "", et_verify_code.getText());
                        presenter.start();
                    } else {
                        BusinessUtil.sendReportByClickType(getApplication(),isEmail? FunctionNameFindId.EmailSetting_ClickSave.getStringValue():FunctionNameFindId.MobileSetting_ClickSave.getStringValue());
                        validateNotifyCode();
                    }
                }
            }
        });
        btn_get_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (presenter.verifyInput(et_new_user_info, isEmail)) {
                    isGetCode = true;
                    et_verify_code.setText("");
                    if (!isFromNotify) {
                        presenter.setUserInfo(isEmail ? et_new_user_info.getText() : "", !isEmail ? et_new_user_info.getText() : "", "");
                        presenter.start();
                    } else {
                        BusinessUtil.sendReportByClickType(getApplication(),isEmail? FunctionNameFindId.EmailSetting_GetVerificationCode.getStringValue():FunctionNameFindId.MobileSetting_GetVerificationCode.getStringValue());
                        getNotifyCode();
                    }
                }
            }
        });
    }

    public void validateNotifyCode() {
        NotifyCodeReq req = genCodeReq();
        req.setSecCode(et_verify_code.getText());
        presenter.validateNotifyCode(req);
    }

    public void setNotifyConfig() {
        if (!CommonUtil.isNull(mNotifyConfigRes)) {
            if (isEmail) {
                mNotifyConfigRes.setMail(et_new_user_info.getText());
            } else {
                mNotifyConfigRes.setPhone(et_new_user_info.getText());
            }
            presenter.setNotifyConfig(mNotifyConfigRes);
        }

    }

    @NonNull
    private NotifyCodeReq genCodeReq() {
        NotifyCodeReq req = new NotifyCodeReq();
        String userInfo = et_new_user_info.getText();
        if (isEmail) {
            req.setEmailAddress(userInfo);
            req.setDestType(NotifyPresenter.IBType.DEST_TYPE_E);
        } else {
            req.setMobilePhoneNumber(userInfo);
            req.setDestType(NotifyPresenter.IBType.DEST_TYPE_S);
        }
        return req;
    }

    public void getNotifyCode() {
        NotifyCodeReq req = genCodeReq();
        presenter.getNotifyCode(req);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        btnBackClick(top_layout);
        if (isFirstLoad()) {
            presenter = new ChangeEmailOrPhonePresenter(((MoreActivity) getActivity()).getScheduler());
            presenter.setView(ChangeEmailOrPhoneFragment.this);

            if (getArguments() != null) {

                isEmail = getArguments().getBoolean("isEmail", false);
                mNotifyConfigRes = (NotifyConfigRes) getArguments().getSerializable(NotifyPresenter.IBType.CHANGE_FROM_NOTIFY);
                isFromNotify = !CommonUtil.isNull(mNotifyConfigRes);

                if (isEmail) {
                    top_layout.setTopTitle(isFromNotify ? getString(R.string.notify_setting_warm_email) : getString(R.string.udpate_emial));
                    tv_user_info.setText(R.string.old_email);
                    et_new_user_info.setInputType(InputType.TYPE_CLASS_TEXT);
                    et_new_user_info.setEditTextHint(R.string.new_email_hint);
                } else {
                    top_layout.setTopTitle(isFromNotify ? getString(R.string.notify_setting_warm_phone) : getString(R.string.udpate_phone));
                    tv_user_info.setText(R.string.old_mobile);
                    et_new_user_info.setInputType(InputType.TYPE_CLASS_PHONE);
                    et_new_user_info.setEditTextHint(R.string.new_mobile_hint);
                    if(!TextUtils.isEmpty(phoneNum)){
                        et_new_user_info.setText(phoneNum);
                        phoneNum = null;
                    }
                }

                tip_tv.setText(isFromNotify ? isEmail ? getString(R.string.notify_setting_warm_email_tip) : getString(R.string.notify_setting_warm_tip) : getString(R.string.personal_change_info_des));
                btn_submit.setText(isFromNotify ? getString(R.string.notify_setting_warm_save) : getString(R.string.btn_submit1));

                String jumpValue = getArguments().getString("jumpValue");
                if (!CommonUtil.isNull(jumpValue)) {
                    tv_user_info_value.setText(CommonUtil.replaceString(jumpValue, isEmail));
                    user_info_layout.setVisibility(View.VISIBLE);
                } else {
                    user_info_layout.setVisibility(View.GONE);
                }
                if(isFromNotify){
                    top_layout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            BusinessUtil.sendReportByClickType(getApplication(), isEmail?FunctionNameFindId.EmailSetting_ClickBack.getStringValue():FunctionNameFindId.MobileSetting_ClickBack.getStringValue());
                             back();
                        }
                    });
                }
            } else {
                throw new NullPointerException();
            }
        }
    }

    @Override
    public void setLoading(boolean isLoading) {
        et_verify_code.setEditEnabled(!isLoading);
//        et_new_user_info.setEditEnabled(!isLoading);

        if (CommonUtil.isNull(et_verify_code.getText())) {
            et_verify_code.showLoading(isLoading);
        } else {
            btn_submit.showLoading(isLoading);
        }
    }

    @Override
    public void verifyResult(View view, int errorResId) {
        if (view instanceof CommonInputLayout) {
            CommonInputLayout inputLayout = (CommonInputLayout) view;
            inputLayout.setEnabled(true);
//            inputLayout.setEditEnabled(true);
            if (errorResId == FinalConstants.Register.NO_ERROR) {
                inputLayout.setCheckHintText(null);
                inputLayout.setEditEnabled(false);
            } else if (errorResId == FinalConstants.Register.CHECK_OK) {
                inputLayout.showLoading(false);
                inputLayout.setRightIcon(R.drawable.onstar_joinme_check_ok);
            } else if (errorResId == FinalConstants.Register.CHECK_CANCEl) {
                inputLayout.setRightIcon(-1);
                inputLayout.showLoading(false);
            } else if (errorResId == FinalConstants.Register.SHOW_LOADING) {
                inputLayout.showLoading(true);
            } else {
                inputLayout.setCheck(false);
                inputLayout.setCheckHintText(errorResId);
            }
        }
    }

    @Override
    public void onNotifyProcess(int what, Object... args) {
        if (args == null)
            return;
        if (processException(args)) return;
        processResponse(what, args[0]);
    }

    private boolean processException(Object[] args) {
        if (args.length > 0) {
            if (args[0] instanceof OnStarException) {
                AlertDialogUtil.showDialogByOnstarException(getActivity(), (OnStarException) args[0]);
                isGetCode = false;
                return true;
            }
        }
        return false;
    }

    private void processResponse(int what, Object arg) {
        BaseResponse response = (BaseResponse) arg;
        boolean isSucceed = response.code.equals("E0000");
        switch (what) {
            case GET_CODE:
                onGetCodeResponse(response, isSucceed);
                break;
            case VALIDATE_CODE:
                onValidateCodeResponse(response, isSucceed);
                break;
            case SET_CONFIG:
                onChangeConfigResponse(isSucceed);
                break;
        }
    }

    private void onChangeConfigResponse(boolean isSucceed) {
        if (isSucceed) {
            ToastUtil.showShort(getActivity(), R.string.notify_setting_change_success);
            Intent it = new Intent();
            it.putExtra(isEmail?"resultEmail":"resultPhone",et_new_user_info.getText());
            it.putExtra("isEmail",isEmail);
            getActivity().setResult( getActivity().RESULT_OK, it);
            phoneNum = "";
            getActivity().finish();

//            back();
        } else {
            ToastUtil.showShort(getActivity(), R.string.notify_setting_change_failed);
        }
    }

    private void onValidateCodeResponse(BaseResponse response, boolean isSucceed) {
        if (isSucceed) {
            setNotifyConfig();
        } else {
            ToastUtil.show(getActivity(), response.description + "");
        }
    }

    private void onGetCodeResponse(BaseResponse response, boolean isSucceed) {
        if (isSucceed) {
            isGetCode = false;
            btn_get_code.start(R.string.again_send);
        } else {
            ToastUtil.show(getActivity(), response.description + "");
        }
    }


    @Override
    public void onResponseError(OnStarException e) {
        AlertDialogUtil.showDialogByOnstarException(getActivity(), e);
        isGetCode = false;
    }

    @Override
    public void onReponseSuccess(RegisterToVisitorResponse object) {
        if (isGetCode) {
            if (isEmail) {
                if (!CommonUtil.isNull(object.getIsEmailUnique()) && object.getIsEmailUnique().equalsIgnoreCase("false")) {
                    verifyResult(et_new_user_info, R.string.SB022_MSG002);
                    return;
                }
            } else {
                if (!CommonUtil.isNull(object.getIsMobileUnique()) && object.getIsMobileUnique().equalsIgnoreCase("false")) {
                    verifyResult(et_new_user_info, R.string.SB022_MSG001);
                    return;
                }
            }
            btn_get_code.start(R.string.again_send);
            isGetCode = false;
        } else {
            AlertDialogUtil.showAlertDialog(getActivity(), R.string.dialog_warning, isEmail ? R.string.update_email_success : R.string.update_mobile_success, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                    back();
                }
            });
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        phoneNum = et_new_user_info.getText();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        phoneNum = null;
    }

    @Override
    public Activity onActivity() {
        return getActivity();
    }
}
